package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService{
    private String localDir = "/user/local/src/images";
    private String urlPath = "http://image.jt.com";

    @Override
    @Transactional
    public ImageVO upload(MultipartFile file) {
        String filename = file.getOriginalFilename().toLowerCase();
        //校验图片格式
        if(!filename.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }
        try {//校验是否为图片类型，用宽和高属性非零校验,IO异常try-catch
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width==0 || height==0){
                return null;
            }
            String dateDir = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String dirPath = localDir + dateDir;
            File dirFile = new File(dirPath);
            if (!dirFile.exists()){
                dirFile.mkdirs();
            }
            //用uuid替换图片名称，保证唯一
            int index = filename.lastIndexOf(".");
            String fileType = filename.substring(index);//得到图片后缀
            String newfilename = UUID.randomUUID().toString()
                                .replace("-", "")+fileType;//生成新文件名称
            String path = dirPath + newfilename;
            file.transferTo(new File(path));//文件上传

            String virtualPath = dateDir + newfilename;//虚拟路径 /yyyy/MM/dd/xxx.jpg
            String fileNameVO = newfilename;//文件名称 xxx.jpg
            String url = urlPath+virtualPath;//网络路径 http://image.jt.com/yyyy/MM/dd/xxx.jpg
            System.out.println(url);
            return new ImageVO(virtualPath,url,fileNameVO);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteFile(String virtualPath) {
        String path = localDir + virtualPath;//准备全文件路径
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
}
